import axios from 'axios'
//默认超时时间
axios.defaults.timeout = 50000;
//统一请求前缀
// axios.defaults.baseURL = 'http://119.253.65.194:17000/v1'
const axiosInstance1 = axios.create({
    baseURL: 'http://119.253.65.194:17000/v1'
  });
const baseUrl2 = 'http://119.253.65.194:8001/v1'
const axiosInstance2 = axios.create({
    baseURL: baseUrl2
  });
function f_base_get(url, params) {
    return new Promise((resolve, reject) => {
        axiosInstance2.get(url, {params:params})
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err)
            })
    })
}
function f_base_post(url, params, formData) {
    return new Promise((resolve, reject) => {
        if (formData) {
            const formData = new URLSearchParams();
            for (const [key, value] of Object.entries(params)) {
                formData.append(key, value);
            }
            axiosInstance1.post(url, formData, {
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                }
            })
                .then(res => {
                    resolve(res.data);
                })
                .catch(err => {
                    reject(err);
                });
        } else {
            axiosInstance1.post(url, params)
                .then(res => {
                    resolve(res.data)
                })
                .catch(err => {
                    reject(err)
                })
        }

    })
}
// 流式接口
// 定义一个 AbortController 实例
let controller;

export function streamPost(url, params, onChunkReceived, onMessageEnd) {
    // 创建一个新的 AbortController 实例
    controller = new AbortController();
    const signal = controller.signal;

    return new Promise((resolve, reject) => {
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(params),
            signal // 将 signal 加入到请求选项中
        };

        fetch(baseUrl2 + url, options)
           .then(response => {
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const reader = response.body.getReader();
                const decoder = new TextDecoder();
                let data = '';
                function read() {
                    return reader.read().then(({ done, value }) => {
                        if (done) {
                            if (typeof onMessageEnd === 'function') {
                                onMessageEnd();
                            }
                            resolve(data);
                            return;
                        }
                        const chunk = decoder.decode(value);
                        data += chunk;
                        // 调用回调函数，实时处理数据块
                        if (typeof onChunkReceived === 'function') {
                            let d_1 = { response_data: '', session_id: '', reasoning_content: '', content: '' };
                            chunk.split('data: ').forEach(item => {
                                if (item) {
                                    const { response_data, session_id, reasoning_content, content } = JSON.parse(item);
                                    d_1.response_data += response_data;
                                    d_1.session_id = session_id;
                                    d_1.reasoning_content += reasoning_content;
                                    d_1.content += content;
                                }
                            });

                            const { response_data, session_id, reasoning_content, content } = d_1;
                            onChunkReceived({
                                text: response_data,
                                session_id,
                                reasoning_content,
                                content
                            });
                        }
                        return read();
                    });
                }

                return read();
            })
           .catch(err => {
                if (err.name === 'AbortError') {
                    console.log('请求已中断');
                } else {
                    reject(err);
                }
            });
    });
}

// 定义一个函数来中断请求
export function abortStreamPost() {
    if (controller) {
        controller.abort();
    }
}

//  将Promise 的错误统一捕获
export async function POST(url, params, formData) {
    let back = null
    try {
        back = await f_base_post(url, params, formData)
    } catch (e) {
        if (e?.response.data === 'The CSRF token is missing.') {
            console.log('CSRF token miss, try again')
            back = await POST(url, params, formData)
        }
        // console.log('async post', e)
    }
    return back
}

export async function GET(url, params) {
    let back = null
    try {
        back = await f_base_get(url, params)
    } catch (e) {
        console.log(e);
    }
    return back
}
